﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Reward : MonoBehaviour {

	private float floatDelay;
	private float floatH;
	private bool isLow;
	private float currentDelay;
	private float preOffX;
	private float floatSpeed;
	[HideInInspector]
	public float width;
	public int score;
	[HideInInspector]
	public float baseY;
	public List<Sprite> list;
	private int animationIndex;
	private bool playAnimation;
	private float playTime;
	// Use this for initialization
	public void Init () {
		width = GetComponent<SpriteRenderer> ().bounds.size.x;
		isLow = true;
		floatDelay = Random.Range (0f, 0.5f);
		floatH = Random.Range (0f, 0.1f);
		floatSpeed = Random.Range (0f, 0.1f);;
		currentDelay = 0f;
		playAnimation = false;
		playTime = 0f;
	}
	
	void Update () {
		if (currentDelay < floatDelay) {
			currentDelay += Time.deltaTime;
		}
		if (currentDelay >= floatDelay) {
			if (isLow) {
				transform.position = new Vector3 (transform.position.x, transform.position.y - floatSpeed * Time.deltaTime, transform.position.z);
			} else {
				transform.position = new Vector3 (transform.position.x, transform.position.y + floatSpeed * Time.deltaTime, transform.position.z);
			}
			if (transform.position.y <= baseY-floatH / 2) {
				isLow = false;
			} else if (transform.position.y >= baseY+floatH / 2) {
				isLow = true;
			}
		}
		if (playAnimation) {
			playTime += Time.deltaTime;
			if (animationIndex == 0 || animationIndex == 5 || animationIndex == 4) {
				if (playTime > 0.1f) {
					animationIndex += 1;
					GetComponent<SpriteRenderer> ().sprite = list [animationIndex];
				}
			} else if (animationIndex == 1 || animationIndex == 2 || animationIndex == 3) {
				if (playTime > 0.05f) {
					animationIndex += 1;
					GetComponent<SpriteRenderer> ().sprite = list [animationIndex];
				}
			} else {
				GetComponentInParent<RewardGroup> ().rewardList.Remove (this);
				Destroy (gameObject);
			}
		}
	}

	void OnTriggerEnter2D(Collider2D collider){
		if (collider.transform.parent != null && collider.transform.parent.name == "Player") {
			playAnimation = true;
			animationIndex = 0;
			RewardScroe ();
			AudioManager.instance.PlayAudioEffect ("reward");
			GetComponent<SpriteRenderer> ().sprite = list [animationIndex];
		}
	}

	public void RewardScroe(){
		var counter = GameObject.Find ("Canvas").GetComponent<ScoreCounter>();
		counter.AddScore (score);
	}
}
